package com.xu.blog_after_end.web;

import com.xu.blog_after_end.service.BlogService;
import com.xu.blog_after_end.service.TagService;
import com.xu.blog_after_end.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class IndexController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;
    @GetMapping("/")  // 访问根页面反回到index页面
    public String index(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,     // 分页查询，默认每页大小为8，按更新时间降序排列
                        Model model){
        model.addAttribute("page",blogService.listBlog(pageable));  // 分页查询博客
        model.addAttribute("types",typeService.listTypeTop(6)); // 查询所有分类
        model.addAttribute("tags",tagService.listTagTop(10)); // 查询推荐博客
        model.addAttribute("recommendBlogs",blogService.listRecommendBlogTop(8));   // 查询推荐博客
        return "index";
    }
    @PostMapping("/search")
    public String search(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,     // 分页查询，默认每页大小为8，按更新时间降序排列
                         @RequestParam String query, Model model){
        model.addAttribute("page",blogService.listBlog("%"+query+"%",pageable));    // 分页查询博客
        model.addAttribute("query",query);  // 搜索关键字
        return "search";
    }
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){  // 访问博客页面 Long id  类型
        model.addAttribute("blog",blogService.getAndConvert(id));
        return "blog";
    }
    @GetMapping("/newblog")  // 访问根页面反回到index页面
    public String newblog(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,     // 分页查询，默认每页大小为8，按更新时间降序排列
                        Model model){
        model.addAttribute("tags",tagService.listTagTop(3)); // 查询推荐博客
        return "index";
    }
}
